<?php

namespace Admin\Controller;

use Think\Controller;

class UserController extends Controller
{
    /**
     * 注册页面
     */
//    public function ajax_register()
//    {
//        $User = M('User');
//        if (IS_AJAX) {
//            $data['username'] = trim(I('post.username'));
//            $data['mobile'] = I('post.mobile');
//            $data['email'] = I('post.email');
//            $data['password'] = set_password(I('post.password'));
//            $check_password = I('post.check_password');
//
//            $preg_email = "/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/";
//            $preg_mobile = "/^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$/";
//
//            $info = array('status' => 1, 'msg' => '注册成功');
//
//            if (strlen($data['username']) < 5 || strlen($data['username']) > 20) {
//                $info = array('status' => 0, 'msg' => '用户名的长度不能小于5位或大于20位');
//            }
//            if (!preg_match($preg_mobile, $data['mobile'])) {
//                $info = array('status' => 0, 'msg' => '手机号格式不正确');
//            }
//            if (!preg_match($preg_email, $data['email'])) {
//                $info = array('status' => 0, 'msg' => '邮箱格式不正确');
//            }
//            if (strlen(I('post.password')) < 6) {
//                $info = array('status' => 0, 'msg' => '密码的长度不能小于6位');
//            }
//            if ($check_password != I('post.password')) {
//                $info = array('status' => 0, 'msg' => '两次输入的密码不一致');
//            }
//
//            //判断用户名，邮箱，手机号是否唯一
//            $username = $User->where("username = '$data[username]'")->find();
//            $mobile = $User->where("mobile = '$data[mobile]'")->find();
//            $email = $User->where("email = '$data[email]'")->find();
//
//            if ($username) {
//                $info = array('status' => 0, 'msg' => '用户名已存在');
//            }
//            if ($mobile) {
//                $info = array('status' => 0, 'msg' => '手机号已存在');
//            }
//            if ($email) {
//                $info = array('status' => 0, 'msg' => '邮箱已存在');
//            }
//
//            if ($info['status'] == 1) {
//                $User->add($data);
//            }
//
//            $this->ajaxReturn($info);
//        } else {
//            $this->display();
//        }
//    }

    /**
     * 用户登录
     */
    public function login()
    {
        $User = M('User');
        $LoginFailed = D('LoginFailed');
        if (IS_POST) {
            $data['username|mobile|email'] = trim(I("post.username"));
            $data['password'] = set_password(I('post.password'));
//            $code = I('post.code');
            $remember = I('post.remember');

            $token = make_token();    //生成token
            $User->where($data)->setField('token', $token);

            //判断验证码是否正确
//            if (!$this->check_verify($code)) {
//                $this->error('验证码不正确');
//            }
            //1个小时内登录失败次数达到了5次
            if (!$LoginFailed->check_failed_times()) {
                $this->error('你登录的错误次数超过5次，请1个小时后再登录');
            }
            //判断用户名和密码是否正确
            $user = $User->where($data)->find();
            if (!$user) {
                $LoginFailed->update_failed_times();
                $this->error('用户名或密码不正确！！');
            }

            //判断账号是否被禁用
            if ($user['status'] == 0) {
                $this->error('你的账号已禁用，请联系管理员');
            }

            if ($remember) {
                setcookie('token', $user['token'], time() + 60 * 60 * 24 * 7, '/');
            } else {
                setcookie('token', $user['token'], null, '/');
            }

            $this->success('登录成功', U('Index/index'));
        } else {
            $this->display();
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
//        rm_dir(RUNTIME_PATH);  使用cookie之前的退出

        $_SESSION = array();
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), "", time() - 3600, "/");
        }
        //彻底销毁session, 注意不要只使用这个函数, 它并不会删除服务器中的session数组和cookie, 所以需要结合以上使用.
        session_destroy();

        $this->success('退出成功', U('User/login'));
    }

    /**
     * 验证码
     */
    function verify()
    {
        $config = array(
            'fontSize' => 30,    // 验证码字体大小
            'length' => 4,     // 验证码位数
            'useNoise' => false, // 关闭验证码杂点
            'codeSet' => '0123456789' //纯数字验证
        );
        $Verify = new \Think\Verify($config);
        $Verify->entry();
    }

    // 检测输入的验证码是否正确，$code为用户输入的验证码字符串
//    function check_verify($code, $id = '')
//    {
//        $verify = new \Think\Verify();
//        return $verify->check($code, $id);
//    }
    //在前台用validate.js的方法验证验证码
    function check_verify($code, $id = '')
    {
        $code = I('get.code');
        $verify = new \Think\Verify();
        $this->ajaxReturn($verify->check($code, $id));
    }

    /**
     * 发送修改密码邮件
     */
    public function password_reset()
    {
        $this->display();
    }

    /**
     * 找回密码
     */
    public function find_pwd()
    {
        $map['email'] = $_POST['email'];
        $token = make_token();  //生成token
        M('User')->where($map)->setField('token', $token);
        $info = M('User')->where($map)->find();
//		dump($info['token']);exit;
        if ($info) {
            $url = $_SERVER ['HTTP_HOST'] . U('User/password_edit') . '?token=' . $info['token'];
            // 调用发送邮件函数,跳到修改密码页面
            $username = $info ['username'];
            $title = "找回密码";

            $content = "<h3>亲爱的：$username 用户</h3>
            <br><br>http://$url
			<br><br><br><h4>有效期30分钟</h4>
			<br><br>
			<img src='__PUBLIC__/images/qq.png'>";

            $from = "164875052@qq.com"; //修改为你的发送邮箱
            $to = $info ['email'];
            $status = send_mail($title, $content, $from, $to);
            if ($status == 1) {
                $this->success('发送邮件成功,请登录邮箱重设密码~', U('User/password_reset'), 2);
            } else {
                $this->error('发送邮件失败...');
                exit ();
            }
        } else {
            $this->error('此邮箱未注册');
            exit ();
        }
    }

    /**
     * 修改密码
     */
    public function password_edit()
    {
        $_SESSION ['userToken'] = array(
            'token' => trim($_GET ['token'])
        );
        $this->display();
    }

    /**
     * 执行修改密码
     */
    public function doeditpwd()
    {
        if (IS_AJAX) {
            $password = I('post.password');
            $check_password = I('post.check_password');

            if (strlen($password) < 6) {
                $info = array('status' => 0, 'msg' => '密码不能小于6位');
            } elseif (strlen($check_password) < 6) {
                $info = array('status' => 0, 'msg' => '确认密码不能小于6位');
            } elseif ($password != $check_password) {
                $info = array('status' => 0, 'msg' => '两次密码输入不一致');
            } else {
                $token = implode("", $_SESSION['userToken']); //将数组转换成字符串
                $userInfo = M('User')->where("token = $token")->find(); //查出数据库中当前token对应的用户
                $str = set_password(I('post.password')); //对表单提交过来的密码做截取处理。
                M('User')->where("id = '$userInfo[id]'")->setField('password', $str);
                $info = array('status' => 1, 'msg' => '修改成功');
            }
            $this->ajaxReturn($info);
        }

    }

}